<template>
  <div>
<!--    查询条件-->
    <el-card style="margin-bottom: 10px">
      <template #header>
        <span>查询条件</span>
      </template>
      <el-form label-width="auto">
        <el-row justify="space-between">
          <el-col :span="8">
            <el-form-item label="姓名">
              <el-input v-model="queryParams.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出生日期">
              <el-date-picker
                  style="width: 400px"
                  v-model="queryParams.age"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="display: flex;justify-content: right">
            <el-form-item label="性别">
              <el-select v-model="queryParams.sex">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between">
          <el-col :span="8">
            <el-form-item label="手机号">
              <el-input v-model="queryParams.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入党时间">
              <el-date-picker
                  v-model="queryParams.join_time"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  style="width: 400px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="display: flex;justify-content: right">
            <el-form-item label="工作单位">
              <el-input v-model="queryParams.work_unit"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between">
          <el-col :span="8">
            <el-form-item label="职位">
              <el-input v-model="queryParams.position"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作状态">
              <el-select v-model="queryParams.work_status">
                <el-option label="在职" value="在职"></el-option>
                <el-option label="无业" value="无业"></el-option>
                <el-option label="自由职业" value="自由职业"></el-option>
                <el-option label="退休" value="退休"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="text-align: right">
            <el-button size="small" type="primary" icon="el-icon-search" @click="Query(1)">查询</el-button>
            <el-button size="small" type="primary" icon="el-icon-delete" @click="Reset">重置</el-button>
          </el-col>
        </el-row>
<!--        <el-row justify="space-between"></el-row>-->
      </el-form>
    </el-card>
<!--    查询结果-->
    <el-card>
      <template #header>
        <div style="display: flex;justify-content: space-between">
          <div>
            <span>查询结果</span>
          </div>
          <div style="display: flex;justify-content: right;">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="showAdd">新增党员信息</el-button>
            <el-upload :show-file-list="false" style="margin-left: 10px" ref="upload" action="#" :on-change="handleChange" accept=".xlsx" :multiple="false" :auto-upload="false">
              <el-button slot="trigger" type="primary" size="small">批量导入</el-button>
            </el-upload>
            <el-button style="margin-left: 10px" type="primary" size="small" @click="exportExcel">全部导出</el-button>
          </div>
        </div>
      </template>
      <el-table style="margin-bottom: 10px" :data="odata" border>
        <el-table-column prop="name" label="姓名" align="center">
        </el-table-column>
        <el-table-column prop="age" label="年龄" align="center">
        </el-table-column>
        <el-table-column prop="sex" label="性别" align="center">
        </el-table-column>
        <el-table-column prop="phone" label="手机号" align="center">
        </el-table-column>
        <el-table-column prop="join_time" label="入党时间" align="center">
        </el-table-column>
        <el-table-column prop="work_unit" label="工作单位" align="center">
        </el-table-column>
        <el-table-column prop="position" label="职位" align="center">
        </el-table-column>
        <el-table-column prop="work_status" label="工作状态" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button style="color: #e72f2f" type="text" size="small" @click="showDialog(scope.row, 2)">编辑</el-button>
            <el-button size="small" type="text" style="color: #e72f2f" @click="showDialog(scope.row, 3)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex;justify-content: right">
        <el-pagination
            background
            layout="total, prev, pager, next, jumper"
            :total="total"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
<!--    <el-row style="margin-top: 30px; margin-left: 30px">-->
<!--      <el-form :inline="true" ref="sel_form">-->
<!--        <el-form-item label="">-->
<!--          <el-input placeholder="请输入姓名" v-model="search_data" class="input-with-select">-->
<!--            <el-button slot="append" type="primary" icon="el-icon-search" @click="fuzzySearch(search_data)">搜索</el-button>-->
<!--          </el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          &lt;!&ndash; 添加按钮DOM &ndash;&gt;-->
<!--          <el-form-item>-->
<!--            <el-button style="background-color: #e72f2f; color: white" @click="showAdd()">新增</el-button>-->
<!--          </el-form-item>-->
<!--          &lt;!&ndash; 筛选按钮DOM &ndash;&gt;-->
<!--          <el-form-item>-->
<!--            <el-button style="background-color: #e72f2f; color: white" @click="showFilter()">筛选</el-button>-->
<!--          </el-form-item>-->
<!--          <el-form-item>-->
<!--            <el-button style="background-color: #e72f2f; color: white" @click="SelectAllMethod()">清除筛选</el-button>-->
<!--          </el-form-item>-->
<!--          &lt;!&ndash; 导入数据DOM &ndash;&gt;-->
<!--          <el-form-item>-->
<!--            <el-upload class="upload-demo" ref="upload" action="#" :on-change="handleChange" accept=".xlsx" :multiple="false" :show-file-list="false" :auto-upload="false">-->
<!--              <el-button slot="trigger" style="background-color: #e72f2f; color: white">导入数据</el-button>-->
<!--            </el-upload>-->
<!--          </el-form-item>-->
<!--          &lt;!&ndash; 导出数据DOM &ndash;&gt;-->
<!--          <el-form-item>-->
<!--            <el-button style="background-color: #e72f2f; color: white" @click="exportExcel">导出数据</el-button>-->
<!--          </el-form-item>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--    </el-row>-->
    <!-- 删除对话框 -->
    <el-dialog title="删除党员信息" :visible.sync="deleteDialog" width="30%">
      <span>确定要删除这条信息吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialog = false">取 消</el-button>
        <el-button type="primary" @click="DeleteMethod(currentOpt._id)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog title="修改党员信息" :visible.sync="updateDialog" width="30%">
      <el-form :model="form">
        <el-form-item label="党员姓名" :label-width="formLableWidth">
          <el-input v-model="currentOpt.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" :label-width="formLableWidth">
          <el-input v-model="currentOpt.phone"></el-input>
        </el-form-item>
        <el-form-item label="党员性别" :label-width="formLableWidth">
          <el-select v-model="currentOpt.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" :label-width="formLableWidth">
          <el-date-picker v-model="currentOpt.age" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="入党时间" :label-width="formLableWidth">
          <el-date-picker v-model="currentOpt.join_time" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="工作单位" :label-width="formLableWidth">
          <el-input v-model="currentOpt.work_unit"></el-input>
        </el-form-item>
        <el-form-item label="现任职位" :label-width="formLableWidth">
          <el-input v-model="currentOpt.position"></el-input>
        </el-form-item>
        <el-form-item label="工作状态" :label-width="formLableWidth">
          <el-select v-model="currentOpt.work_status" placeholder="请选择工作状态">
            <el-option label="在职" value="在职"></el-option>
            <el-option label="无业" value="无业"></el-option>
            <el-option label="自由职业" value="自由职业"></el-option>
            <el-option label="退休" value="退休"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialog = false">取 消</el-button>
        <el-button type="primary" @click="UpdateMethod(currentOpt)">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加对话框 -->
    <el-dialog title="添加党员信息" :visible.sync="addDialog" width="30%">
      <el-form :model="form">
        <el-form-item label="党员姓名" :label-width="formLableWidth">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" :label-width="formLableWidth">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="党员性别" :label-width="formLableWidth">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" :label-width="formLableWidth">
          <el-date-picker v-model="form.age" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入党时间" :label-width="formLableWidth">
          <el-date-picker v-model="form.join_time" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="工作单位" :label-width="formLableWidth">
          <el-input v-model="form.work_unit"></el-input>
        </el-form-item>
        <el-form-item label="现任职位" :label-width="formLableWidth">
          <el-input v-model="form.position"></el-input>
        </el-form-item>
        <el-form-item label="工作状态" :label-width="formLableWidth">
          <el-select v-model="form.work_status" placeholder="请选择工作状态">
            <el-option label="在职" value="在职"></el-option>
            <el-option label="无业" value="无业"></el-option>
            <el-option label="自由职业" value="自由职业"></el-option>
            <el-option label="退休" value="退休"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="AddMethod(form)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
export default {
  mounted() {
    this.Query(1);
  },
  data() {
    return {
      // 查询用户信息表单
      total:0,
      queryParams:{
        name: "",
        sex: "",
        age: "",
        phone: "",
        work_status: "",
        work_unit: "",
        position: "",
        join_time: "",
        pageNo: 1
      },
      currentOpt: {
        _id: "",
        name: "",
        sex: "",
        age: "",
        phone: "",
        work_status: "",
        work_unit: "",
        position: "",
        join_time: "",
      },
      // 添加党员的表单数据
      form: {
        name: "",
        phone: "",
        sex: "",
        age: "",
        join_time: "",
        work_unit: "",
        work_status: "",
        position: "",
      },
      //添加对话框style
      formLableWidth: "80px",
      //展示所有用户信息数组
      odata: [],
      odata1: [],
      // 几种对话框的标志位
      deleteDialog: false,
      updateDialog: false,
      filterDialog: false,
      addDialog: false,
      //展示所有用户信息数组的长度
      odataLength: 0,
    };
  },
  methods: {
    // 切换页号
    handleCurrentChange(val){
      this.Query(val);
    },
    // 重置
    Reset(){
      this.queryParams = {
        name: "",
        sex: "",
        age: "",
        phone: "",
        work_status: "",
        work_unit: "",
        position: "",
        join_time: "",
        pageNo: 1
      };
    },
    // 查询用户信息接口
    async Query(pageNo) {
      this.queryParams.pageNo = pageNo;
      // 初始化前端表格
      this.odata = [];
      this.odata1 = [];
      const res = await this.$axios({
        url: "/api/userlist",
        method: "post",
        data:this.queryParams
      });
      if(res && res.status===200){
        this.total = res.data.pager.Total;
        for(let i=0;i<res.data.data.length;i++){
          const temp = JSON.parse(res.data.data[i]);
          this.odata1.push({_id:temp._id,age:temp.age});
          temp.age = this.AgeMethod(temp.age);
          this.odata.push(temp);
        }
      }
    },
    // 删除用户接口
    async DeleteMethod(_id) {
      this.deleteDialog = false;
      // console.log(_id);
      let res = await this.$axios({
        url: "/api/deleteuserlist",
        method: "post",
        data: {
          _id,
        },
      });
      // console.log(res);
      if (res && res.data.status === 1) {
        this.Query(1);
        this.$message({
          showClose: true,
          message: "删除成功",
          type: "success",
        });
      } else {
        this.$message({
          showClose: true,
          message: "删除失败",
          type: "error",
        });
      }
    },
    // 修改用户接口
    async UpdateMethod(currentOpt) {
      this.updateDialog = false;
      // console.log(currentOpt);
      let {
        name,
        age,
        sex,
        phone,
        work_status,
        work_unit,
        position,
        join_time,
        _id,
      } = currentOpt;
      // console.log('1111',name,age,sex,work_status,work_unit,position,join_time);
      let res = await this.$axios({
        url: "/api/edituserlist",
        method: "post",
        data: {
          name,
          phone,
          age,
          sex,
          work_status,
          work_unit,
          position,
          join_time,
          _id,
        },
      });
      // console.log(res);
      if (res && res.data.status === 1) {
        this.Query(1);
        this.$message({
          showClose: true,
          message: "恭喜你，修改成功",
          type: "success",
        });
      } else {
        this.$message({
          showClose: true,
          message: "修改失败，请检查是否有空信息",
          type: "error",
        });
      }
    },
    // 添加用户接口
    async AddMethod(form) {
      this.addDialog = false;
      //先写两个方法把年龄计算出来，把入党时间标准化处理一下
      form.age = this.transformDate(form.age);
      form.join_time = this.transformDate(form.join_time);
      form.password = "123456";
      form.image = 'cloud://cloud1-4gfhls3pb83e8f3c.636c-cloud1-4gfhls3pb83e8f3c-1325827386/ca1014ee4f4ff7ce70a5ea82e616d3d.jpg';
      // console.log(form);
      let res = await this.$axios({
        url: "/api/adduserlist",
        method: "post",
        data: {
          form,
        },
      });
      // console.log(res);
      if (res && res.data.status === 1) {
        this.Query(1);
        this.$message({
          showClose: true,
          message: "恭喜你，添加成功",
          type: "success",
        });
      } else {
        this.$message({
          showClose: true,
          message: "添加失败，请检查是否有空信息",
          type: "error",
        });
      }
    },
    //展示对话框
    showDialog(row, index) {
      //1---详情
      //2---修改
      //3---删除
      this.currentOpt._id = row._id;
      this.currentOpt.name = row.name;
      this.currentOpt.sex = row.sex;
      this.currentOpt.phone = row.phone;
      this.currentOpt.join_time = row.join_time;
      this.currentOpt.work_status = row.work_status;
      this.currentOpt.work_unit = row.work_unit;
      this.currentOpt.position = row.position;
      for (let i = 0; i < this.odata1.length; i++) {
        if (this.odata1[i]._id === row._id) {
          this.currentOpt.age = this.odata1[i].age;
        }
      }
      if (index === 1) {
        //详情
        // console.log(row)
        this.detailDialog = true;
      } else if (index === 2) {
        //修改
        this.updateDialog = true;
      } else {
        //删除
        this.deleteDialog = true;
      }
    },
    // 展示添加对话框
    showAdd() {
      this.form = {
        name: "",
        age: "",
        sex: "",
        phone: "",
        join_time: "",
        work_status: "",
        work_unit: "",
        position: "",
      };
      this.addDialog = true;
    },
    //处理时间格式
    transformDate(param) {
      const date = new Date(param);
      // 提取并格式化年、月、日
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以需要+1
      const day = String(date.getDate()).padStart(2, "0"); // 日期可能是1-9，需要补0
      // 组合成年-月-日的格式
      const formattedDate = `${year}-${month}-${day}`;
      return formattedDate;
    },
    //计算年龄
    AgeMethod(param) {
      const birthDate = new Date(param);
      // 获取当前日期
      const today = new Date();
      // 计算年龄
      let age = today.getFullYear() - birthDate.getFullYear();
      // 但是，如果今天还没有到生日那天，我们需要从年龄中减去1
      const m = today.getMonth() - birthDate.getMonth();
      if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }
      return age;
    },
    // 导入数据
    handleChange(file, fileList) {
      let reader = new FileReader();
      reader.onload = async (e) => {
        let data = new Uint8Array(e.target.result);
        let workbook = XLSX.read(data, {
          type: "array",
        });
        // 处理sheet1
        let worksheetName = workbook.SheetNames[0];
        let worksheet = workbook.Sheets[worksheetName];
        let jsonData = XLSX.utils.sheet_to_json(worksheet, {
          header: 1,
        });
        // console.log(jsonData);
        for (let i = 1; i < jsonData.length; i++) {
          this.form.name = jsonData[i][0];
          this.form.sex = jsonData[i][1];
          this.form.age = jsonData[i][2];
          this.form.join_time = jsonData[i][3];
          this.form.work_unit = jsonData[i][4];
          this.form.position = jsonData[i][5];
          this.form.work_status = jsonData[i][6];
          this.form.phone = jsonData[i][7];
          // console.log(jsonData[i]);
          await this.AddMethod(this.form);
        }
      };
      reader.readAsArrayBuffer(file.raw);
    },
    // 导出数据
    exportExcel() {
      // 处理数据
      let tableData = [];
      for (let i = 0; i < this.odata.length; i++) {
        let obj = {};
        obj.name = this.odata[i].name;
        obj.age = this.odata[i].age;
        obj.sex = this.odata[i].sex;
        obj.join_time = this.odata[i].join_time;
        obj.work_unit = this.odata[i].work_unit;
        obj.position = this.odata[i].position;
        obj.work_status = this.odata[i].work_status;
        obj.phone = this.odata[i].phone;
        tableData.push(obj);
      }
      // 将表格数据转换为工作表
      let worksheet = XLSX.utils.json_to_sheet(tableData);
      // console.log(worksheet);
      worksheet.A1.v = "姓名";
      worksheet.B1.v = "年龄";
      worksheet.C1.v = "性别";
      worksheet.D1.v = "入党时间";
      worksheet.E1.v = "工作单位";
      worksheet.F1.v = "职位";
      worksheet.G1.v = "工作状态";
      worksheet.H1.v = "手机号码";
      // 创建新的工作簿并添加到工作表
      let workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
      // 将工作簿写入文件
      let wbout = XLSX.write(workbook, {
        bookType: "xlsx",
        type: "array",
      });
      // 使用file-saver保存文件
      try {
        saveAs(
          new Blob([wbout], {
            type: "application/octet-stream",
          }),
          "党员信息.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
  },
};
</script>
<style scoped>
.hao {
  height: 40px;
  line-height: 40px;
  text-align: center;
}

.a {
  margin-bottom: 30px;
}
.el-input{
  width: 400px;
}
.el-select{
  width: 400px;
}
</style>